package com.example.feidaolumanager.pages.ui.map

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.feidaolu.base.LoadState
import com.example.feidaolumanager.api.RetrofitClient
import com.example.feidaolumanager.pojo.MachineItem
import com.example.feidaolumanager.pojo.User
import kotlinx.coroutines.launch

class MapViewModel : ViewModel() {

    var tokenExpire = MutableLiveData(false)

    val loadState = MutableLiveData<LoadState>()
    val machineInfos = MutableLiveData(listOf<MachineItem>())


    fun getMachineInfos(user: User, selKey: Int? = null, selLevel: Int? = null) {

        loadState.value = LoadState.LOADING
        viewModelScope.launch {
            val resultData = try {
                RetrofitClient.machineService.getMachines(
                    id = user.ss_id,
                    selKey = selKey,
                    selLevel = selLevel,
                    userAccount = user.account,
                    level = user.level.toString()
                )
            } catch (e: Exception) {
                return@launch
            }
            if (resultData.code == com.example.feidaolumanager.Constants.success_code) {
                Log.e(
                    this@MapViewModel.toString(),
                    "getMachineInfos: 获取数据成功${machineInfos.value}",
                )

                machineInfos.value = resultData.data?.records
            } else {
                if (resultData.msg == "401") {
                    // 登录过期，跳转到登录页
                    tokenExpire.value = true
                }
            }

            loadState.value = LoadState.SUCCESS
        }
    }
}